<?php

namespace App\Containers\AppSection\Qualification\Actions;

use App\Containers\AppSection\Log\Tasks\CreateLogTask;
use App\Containers\AppSection\Profile\Tasks\UpdateProfileTask;
use App\Containers\AppSection\Qualification\Models\Qualification;
use App\Containers\AppSection\Qualification\Tasks\CreateRemarkTask;
use App\Containers\AppSection\Qualification\Tasks\FindQualificationByIdTask;
use App\Containers\AppSection\Qualification\Tasks\SendToQualificationTask;
use App\Containers\AppSection\Qualification\Tasks\UpdateQualificationTask;
use App\Ship\Parents\Actions\Action;
use App\Ship\Parents\Requests\Request;

class UpdateQualificationAction extends Action
{
    public function run($id, Request $request): Qualification
    {
        $qualification = app(FindQualificationByIdTask::class)->run($id);

        if ($request->getInputByKey('type') === 'qualification_checking') {
            app(UpdateQualificationTask::class)->run($qualification->id, [
                'unqualified_at' => now()
            ]);

            $qualification = app(SendToQualificationTask::class)->run([
                'profile_id' => $qualification->profile->id,
                'stage' => 'moderator',
                'conditions' => $qualification->conditions,
                'status_key' => $request->getInputByKey('type'),
            ]);

            app(UpdateProfileTask::class)->run($qualification->profile->id, [
                'qualification_status_key' => $request->getInputByKey('type'),
                'qualification_id' => $qualification->id
            ]);
        }

        if (!empty($request->getInputByKey('remarks'))) {
            foreach ($request->getInputByKey('remarks') as $remark) {
                app(CreateRemarkTask::class)->run([
                    'message' => $remark,
                    'qualification_id' => $qualification->id,
                    'profile_id' => $request->profile()->id
                ]);
            }
        }

        $log = '';
        switch ($request->getInputByKey('type')) {
            case 'qualification_checking':
                $log = "Профиль №{$qualification->profile->id} отправлен на повторную квалификацию.";
                break;
        }


        app(CreateLogTask::class)->run($qualification->profile->id, $log, 'qualification', $qualification->id);
        app(CreateLogTask::class)->run($request->profile()->id, $log, 'qualification', $qualification->id);

        return $qualification;
    }
}
